package com.jwiki.app.jkeeper.config;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.jwiki.app.jkeeper.interceptor.ExceptionInterceptor;
import com.jwiki.app.jkeeper.interceptor.SecurityInterceptor;

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

    @Bean
    public SecurityInterceptor securityInterceptor() {
        SecurityInterceptor securityInterceptor = new SecurityInterceptor();
        securityInterceptor.setRedirectUrl("/app/index.html#/login");
        securityInterceptor.setIgnoredUrlPatterns(new HashSet<>(Arrays.asList("/app/**", "/auth/**")));
        return securityInterceptor;
    }

    @Bean
    public ExceptionInterceptor exceptionInterceptor() {
        ExceptionInterceptor exceptionInterceptor = new ExceptionInterceptor();
        int errorCode = HttpStatus.INTERNAL_SERVER_ERROR.value();
        exceptionInterceptor.setDefaultStatusCode(errorCode);
        Properties mappings = new Properties();
        mappings.put(Throwable.class.getName(), errorCode);
        exceptionInterceptor.setExceptionMappings(mappings);
        return exceptionInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(securityInterceptor()).addPathPatterns("/**");
    }

    @Override
    public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
        resolvers.add(exceptionInterceptor());
    }

}
